<template>
    <el-form ref="formRef" :model="formData" :rules="formRules" size="small" :inline="false" label-width="100px">
      <el-form-item label="事项主题" prop="title">
        <el-input v-model="formData.title" placeholder="请填写事项主题" maxlength="32" clearable/>
      </el-form-item>
      <el-form-item label="事项描述" prop="content">
        <editor v-model="formData.content" height="160px"/>
      </el-form-item>
      <el-form-item label="完成期限">
        <div style="max-width: 400px">
          <el-date-picker v-if="dateType" v-model="dateTime" style="width: 100%" type="datetimerange" range-separator="至"
                          start-placeholder="行动开始时间" end-placeholder="行动结束时间" value-format="YYYY-MM-DD HH:mm:ss" @change="selectTime"/>
          <el-date-picker v-else v-model="formData.actionStartTime" type="datetime" style="width: 100%"
                          value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择行动时间"/>
        </div>
        <el-button style="margin-left: 10px" plain :icon="Refresh" @click="dateType = !dateType"/>
      </el-form-item>
      <el-form-item label="执行人" prop="executorIds">
        <el-select v-model="formData.executorIds" placeholder="请选择执行人" size="small" multiple filterable style="width: 100%" @change="executorChange">
          <el-option v-for="item in enterpriseUsers" :key="item.userId" :value="item.userId" :label="item.nickname"/>
        </el-select>
      </el-form-item>
      <el-form-item label="关联">
        <module-relate :relate-items="formData.relateItems"/>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="formData.remark" :rows="3" type="textarea" placeholder="请填写备注"/>
      </el-form-item>
      <el-form-item label="优先度">
        <el-radio-group v-model="formData.priority" size="small">
          <el-radio :label="0" size="small">普通</el-radio>
          <el-radio :label="1" size="small">高</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="通知时间" prop="remindState">
        <el-radio-group v-model="formData.remindState">
          <el-radio v-for="item in remindTimes" :key="item.value" :label="item.value" size="small">{{item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="通知方式" prop="remindType">
        <el-checkbox-group v-model="formData.remindType" size="small">
          <el-checkbox label="1">应用、公众号通知</el-checkbox>
          <el-checkbox label="2">短信通知</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="文档">
        <Document style="width: 100%;" v-if="getCode" :file-group="formData.type" v-model:resultList="resultList" :limit="9"/>
      </el-form-item>
    </el-form>
</template>

<script>
// 方案事项
import {computed, reactive, toRefs, ref, onMounted, watch, nextTick} from 'vue'
import Cookies from 'js-cookie'
import {createMatterJust} from '/@/api/matter'
import Editor from '/@/components/editor/index.vue'
import ModuleRelate from '/@/views/matter/components/ModuleRelate.vue'
import {ElMessage} from 'element-plus'
import {Refresh} from '@element-plus/icons-vue'
import api from '/@/api/commonApi'
import {formatDate} from '/@/utils/formatTime'
import Document from '/@/components/document/index.vue'
import { useCalendarConfig } from '/@/stores/calendar';
import { storeToRefs } from 'pinia';

export default {
    name: 'SchemeForm',
    props: {
        code: {
            type: String,
            default: ''
        },
        relateItem: {
            type: Object,
            default: null
        },
        enterpriseUsers: {
            type: Array,
            default: []
        },
        remindTimes: {
            type: Array,
            default: []
        },
        selectTime: {
            type: String,
            default: null
        },
        editId: {
          type: String,
          default: null
        }
    },
    components: {
        Editor,
        ModuleRelate,
        Document
    },
    setup(props, context) {
        const formRef = ref()
        const {code, relateItem, enterpriseUsers, remindTimes, selectTime, editId} = toRefs(props)
        const storesCalendarConfig = useCalendarConfig();
        const { eventForm } = storeToRefs(storesCalendarConfig)
        const state = reactive({
            resultList: [], // 返回的数据
            formData: {
                title: '方案',
                content: '',
                actionStartTime: null,
                actionEndTime: null,
                executorIds: [],
                relateItems: [],
                remark: null,
                attach: '',
                attachNames: '',
                priority: 0,
                remindState: 'NONE',
                remindType: [],
                type: 'SCHEME'
            },
            formRules: {
                title: {required: true, message: '请填写事项主题', trigger: 'blur'}
            },
            dateType: false,  // 行动时间范围/单时间切换
            dateTime: [],
            selfId: null,
            getCode: false,
            originForm: {}
        })
        const checkCode = computed(() => {
            let flag = code.value == state.formData.type
            if (flag) {
                // 默认带入自己
                state.selfId = Cookies.get('userId')
                state.formData.executorIds = [state.selfId]
                // 行动时间默认现在
                let nowTime = selectTime.value ? selectTime.value : formatDate(new Date(), 'YYYY-mm-dd HH:MM:SS')
                state.formData.actionStartTime = nowTime
                state.dateTime = [nowTime, nowTime]
                if (relateItem.value) {   // 关联项带入
                    state.formData.relateItems = [relateItem.value]
                }
            }
            return flag
        })
        const selectedTime = (val) => {
            if (val && val.length === 2) {
                state.formData.actionStartTime = val[0]
                state.formData.actionEndTime = val[1]
            } else {
                state.formData.actionStartTime = state.formData.actionEndTime = null
            }
        }
        const executorChange = (val) => {
            if (!val.includes(state.selfId)) {
                state.formData.executorIds.push(state.selfId)
                ElMessage.warning('本人必须在执行人中，无法移除')
            }
        }
        const submit = () => {
            if(!formRef) return
            return new Promise((resolve, reject) => {
                formRef.value.validate(valid => {
                    if (!valid) {
                        return false
                    }
                    let params = Object.assign({}, state.formData)
                    // 列表转逗号分割字符串提交
                    state.formData.remindType = params.remindType + ''
                    if (state.resultList.length > 0) {  // 组装附件地址和名称
                        for (let i = 0; i < state.resultList.length; i++) {
                            let item = state.resultList[i]
                            state.formData.attach += item.src
                            state.formData.attachNames += item.name
                            if (i < state.resultList.length - 1) {
                                state.formData.attach += ','
                                state.formData.attachNames += '，'
                            }
                        }
                    }
                    if(editId.value) {
                    // 编辑
                    for(let key in state.formData){
                        if(state.originForm.hasOwnProperty(key)){
                            state.originForm[key] = state.formData[key]
                        }
                        if(state.originForm.info.hasOwnProperty(key)){
                            state.originForm.info[key] = state.formData[key]
                        }
                        }
                        storesCalendarConfig.setEventForm(state.originForm)
                        reset()
                        resolve('edit') 
                    }else{
                        createMatterJust(state.formData).then(res => {
                            if (res.data) {
                                ElMessage.success('提交成功')
                                reset()
                                // 关联事项主键
                                let data = state.resultList.map(item => {
                                item.matterId = res.data.agendaMatterId
                                item.matterName = res.data.title
                                    return item
                                })
                                api.fileRelevanceModule(data)
                                reset()
                                resolve()
                            }
                        }).catch(e => reject(e))
                    }
                })
            })
        }
        const reset = () => {
            if(!formRef) return
            formRef.value.resetFields();
        }
        watch(() => eventForm.value,
          val => {
            if(editId.value && val) {
              // 编辑
              nextTick(() => {
                const data = val
                if(!data) return
                state.originForm = data
                for(let params in data.info){
                  // 拿出info里面的数据
                  if(state.formData.hasOwnProperty(params)) {
                    state.formData[params] = data.info[params]
                  }
                }
                for(let key in data) {
                  // 列表里面的数据
                  if(state.formData.hasOwnProperty(key)) {
                    state.formData[key]= data[key]
                  }
                }
                if(data.remindType){
                  state.formData.remindType = data.remindType.split(',')
                }
                state.selfId = Cookies.get('userId')
                state.formData.executorIds[0] = state.selfId
                if(data.executorIds){
                  state.formData.executorIds.concat(data.executorIds)
                }
              })
            }
          }        
        )
        onMounted(() => {
            state.getCode = checkCode.value
        })
        return{
            ...toRefs(state),
            selectedTime,
            executorChange,
            Refresh,
            formRef,
            submit,
            reset,
            enterpriseUsers,
            remindTimes,
        }
    } 
}
</script>

<style>

</style>